from selenium.webdriver.common.by import By
from selenium import webdriver
import time
import pymysql
n = 1
zhanghao = input("请输入你的账号:")
mima = input("请输入你的密码:")
conn = pymysql.connect(host='localhost', user='root', password='123456', database='spider')
cursor = conn.cursor()
cursor.execute("create table mooc(Id varchar(20),cCourse varchar(20),cCollege varchar(20),cTeacher varchar(20),cTeam varchar(20),cCount varchar(20),cProcess varchar(50),cBrief varchar(1000))")
conn.commit()
sql = "INSERT INTO mooc (Id,cCourse,cCollege,cTeacher,cTeam,cCount,cProcess,cBrief) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"



driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.icourse163.org/")
load = driver.find_element(By.XPATH,'//*[@id="app"]/div/div/div[1]/div[3]/div[3]/div')
load.click()
time.sleep(3)
iframe = driver.find_element(By.XPATH,'/html/body/div[13]/div[2]/div/div/div/div/div/div[1]/div/div[1]/div[2]/div[2]/div[1]/div/iframe')
driver.switch_to.frame(iframe)
driver.find_element(By.XPATH,'/html/body/div[2]/div[2]/div[2]/form/div/div[2]/div[2]/input').send_keys(zhanghao)
driver.find_element(By.XPATH,'/html/body/div[2]/div[2]/div[2]/form/div/div[4]/div[2]/input[2]').send_keys(mima)
driver.find_element(By.XPATH,'/html/body/div[2]/div[2]/div[2]/form/div/div[6]/a').click()
time.sleep(5)
driver.switch_to.default_content()
time.sleep(3)
driver.find_element(By.XPATH,'//*[@id="privacy-ok"]').click()
driver.find_element(By.XPATH,'/html/body/div[4]/div[2]/div[1]/div/div/div[1]/div[1]/div[1]/span[1]/a').click()
driver.switch_to.window(driver.window_handles[-1])
for _ in range(2):
    for i in range(5):
        list = driver.find_element(By.XPATH,f'//*[@id="channel-course-list"]/div/div/div[2]/div[1]/div[{i+1}]/div/div[3]/div[1]').text.split("\n")
        driver.find_element(By.XPATH,f'//*[@id="channel-course-list"]/div/div/div[2]/div[1]/div[{i+1}]').click()
        driver.switch_to.window(driver.window_handles[-1])
        team = driver.find_elements(By.XPATH,'//*[@class="f-fc3"]')
        m = []
        for j in team:
            m.append(j.text)
        m = ','.join(m)
        list.append(m)
        count = driver.find_element(By.XPATH,'//*[@class="count"]').text
        list.append(count[2:-3])
        date = driver.find_element(By.XPATH,'//*[@id="course-enroll-info"]/div/div[1]/div[2]/div/span[2]').text
        list.append(date)
        brief = driver.find_element(By.XPATH,'//*[@id="j-rectxt2"]').text
        list.append(brief)
        values = (n, list[0], list[1], list[2], list[3], list[4], list[5], list[6])
        cursor.execute(sql, values)
        conn.commit()
        n = n+1
        driver.close()
        driver.switch_to.window(driver.window_handles[-1])
    driver.find_element(By.XPATH,'//*[@id="channel-course-list"]/div/div/div[2]/div[2]/div/a[10]').click()
    time.sleep(2)



cursor.close()
conn.close()